using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class Laser : MonoBehaviour
{
    public float max=100;
    [SerializeField] Transform start;
    [SerializeField] Transform end;
    [SerializeField] LineRenderer lineRenderer;

    RaycastHit hit;
    Vector3 direction;
    Vector3 rotateToNormal = new Vector3(0,90,0);
    private void Reset()
    {
        if(start == null)
            start = transform.Find("start");
        if(end == null)
            end = transform.Find("end");
        lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.positionCount = 2;
    }

    private void Update()
    {
        direction = (end.position - start.position).normalized;
        if( Physics.Raycast(start.position, direction,out hit))
        {
            end.position = hit.point;
            end.forward = hit.normal;
            end.Rotate(rotateToNormal);
        }
        else
        {
            end.position = start.position + direction * max;
        }
    }

    private void OnDrawGizmos()
    {
        if (start == null)
            Reset();
        
        if (start == null || end == null)
            return;

        SetPositions();
    }

    void SetPositions()
    {
        lineRenderer.SetPosition(0, start.localPosition);
        lineRenderer.SetPosition(1, end.localPosition);
    }
}
